<template>
  <el-card class="dimension-table-card">
    <DynamicTable
      ref="tableRef"
      :data="dimensionList"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      :selection-type="selectionType"
      row-key="id"
      size="small"
      border
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handlePageChange"
    >
      <template #table-top="">
        <el-button type="primary" @click="handleCreateDimension">
          创建维度
        </el-button>
      </template>
      <template #action="{ row }">
        <el-button size="small" @click="handleViewDetail(row.id)">
          详情
        </el-button>
        <el-button size="small" @click="handleEdit(row.id)"> 编辑 </el-button>
        <el-button size="small" @click="handleDelete(row.id)"> 删除 </el-button>
      </template>
      <template #status="{ row }">
        <el-switch
          v-model="row.is_enabled"
          :active-value="true"
          :inactive-value="false"
          @change="handleStatusChange(row)"
          :loading="row._switching"
        />
      </template>
    </DynamicTable>
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { ElMessageBox } from "element-plus";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicTableInstance } from "@/components/DynamicTable/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";

// 定义属性和事件
const props = defineProps({
  data: {
    type: Array,
    default: () => [],
  },
  loading: {
    type: Boolean,
    default: false,
  },
  pagination: {
    type: Object as () => PaginationConfig,
    required: true,
  },
  selectionType: {
    type: String as () => "none" | "single" | "multiple",
    default: "multiple",
  },
});

const emit = defineEmits([
  "selection-change",
  "size-change",
  "current-page-change",
  "view-detail",
  "edit",
  "enable",
  "disable",
  "delete",
  "handleCreateDimension",
]);

const tableRef = ref<DynamicTableInstance>();

// 格式化函数
const formatCode = (row: any) => {
  return `<span class="monospace-text">${
    row.code || row.dimension_code || "-"
  }</span>`;
};

const formatScore = (row: any) => {
  return `${row.max_score || 0} 分`;
};

// 表格列配置
const columns: TableColumn[] = [
  {
    label: "序号",
    width: 60,
    align: "center",
    render: (row: any, column: any, cellValue: any, index: number) => {
      return index + 1;
    },
  },
  {
    label: "维度名称",
    prop: "name",
    formatter: (row: any) => row.name || row.dimension_name || "-",
  },
  {
    label: "维度代码",
    prop: "code",
    formatter: formatCode,
  },
  {
    label: "所属模板",
    prop: "template_name",
    formatter: (row: any) => row.template_name || "-",
  },
  {
    label: "最大分值",
    prop: "max_score",
    formatter: formatScore,
  },
  {
    label: "权重系数",
    prop: "weight",
    formatter: (row: any) => row.weight || 0,
  },
  {
    label: "显示顺序",
    prop: "sort_order",
    width: 100,
    formatter: (row: any) => row.sort_order || row.display_order || 0,
  },
  {
    label: "状态",
    prop: "status",
    width: 120,
    slot: "status",
  },
  {
    label: "操作",
    width: 220,
    fixed: "right",
    slot: "action",
  },
];

// 计算属性：维度列表
const dimensionList = computed(() => props.data);

// 事件处理
const handleSelectionChange = (selection: any[]) => {
  emit("selection-change", selection);
};

const handleSizeChange = (size: number) => {
  emit("size-change", size);
};

const handlePageChange = (page: number) => {
  emit("current-page-change", page);
};

const handleViewDetail = (id: number) => {
  emit("view-detail", id);
};

const handleEdit = (id: number) => {
  emit("edit", id);
};

const handleDelete = (id: number) => {
  emit("delete", id);
};

const handleCreateDimension = () => {
  emit("handleCreateDimension");
};

const handleStatusChange = async (row: any) => {
  // 防止在切换过程中重复点击
  if (row._switching) {
    // 如果正在切换，回滚状态
    row.is_enabled = !row.is_enabled;
    return;
  }

  const isEnable = row.is_enabled;
  const actionText = isEnable ? "启用" : "禁用";
  const dimensionName = row.name || row.dimension_name || "该维度";

  try {
    await ElMessageBox.confirm(
      `确定要${actionText}维度"${dimensionName}"吗？`,
      `${actionText}确认`,
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 用户确认后，发送状态变更事件
    if (isEnable) {
      emit("enable", row.id, row);
    } else {
      emit("disable", row.id, row);
    }
  } catch {
    // 用户取消操作，回滚状态
    row.is_enabled = !row.is_enabled;
  }
};

// 暴露方法
defineExpose({
  clearSelection: () => tableRef.value?.clearSelection(),
  getSelectionRows: () => tableRef.value?.getSelectionRows() || [],
});
</script>

<style scoped lang="scss">
.dimension-table-card {
  margin-bottom: 16px;
  border-radius: 8px;
}

::v-deep .monospace-text {
  font-family: monospace;
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 13px;
}

.text-warning {
  color: #e6a23c;
}

.text-success {
  color: #67c23a;
}
</style>
